<?php

namespace modules\Cos;

use think\App;
use QCloud\COSSTS\Sts;
use Qcloud\Cos\Client;
use \Exception;
use think\facade\Event;
use app\common\model\Config;
use app\common\model\Attachment;

class Cos
{
    public function AppInit()
    {
        // 上传配置初始化
        Event::listen('uploadConfigInit', function (App $app) {
            $uploadConfig = get_sys_config('', 'upload');
            if ($uploadConfig['upload_mode'] == 'cos') {
                $cdn = $uploadConfig['upload_cdn_url'] == '' ? 'http://'.$uploadConfig['upload_bucket'].'.cos.'.$uploadConfig['upload_url'].'.myqcloud.com' : $uploadConfig['upload_cdn_url'];
                $app->request->upload = [
                    'cdn'    => $cdn,
                    'mode'   => $uploadConfig['upload_mode'],
                    'params' => [
                        'bucket' => $uploadConfig['upload_bucket'],
                        'region' => $uploadConfig['upload_url']
                    ]
                ];
            }
        });

        // 附件管理中删除了文件
        Event::listen('AttachmentDel', function (Attachment $attachment) {
            if ($attachment->storage != 'cos') {
                return true;
            }
            $uploadConfig = get_sys_config('', 'upload');
            if (!$uploadConfig['upload_access_key'] || !$uploadConfig['upload_secret_key'] || !$uploadConfig['upload_bucket']) {
                return true;
            }
            $cosClient = new Client([
                'region' => $uploadConfig['upload_url'],
                'schema' => 'https', //协议头部，默认为http
                'credentials'=> [
                    'secretId'  => $uploadConfig['upload_access_key'] ,
                    'secretKey' => $uploadConfig['upload_secret_key']
                ]
            ]);
            $key                = str_replace(full_url(), '', ltrim($attachment->url, '/'));
            $cosClient->deleteObject([
                'Bucket' => $uploadConfig['upload_bucket'],
                'Key' => $key
            ]);
            return true;
        });
    }

    /**
     * 使用 secretId & secretKey 颁发临时凭证
     * @return array|Sts
     *@var $secretKey string
     * @var $bucket string
     * @var $region string
     * @var $secretId string
     */
    public static function getSts(){
        $uploadConfig = get_sys_config('', 'upload');
        $sts = new Sts();
        $config = [
            'url' => 'https://sts.tencentcloudapi.com/',
            'domain' => 'sts.tencentcloudapi.com',
            'proxy' => '',
            'secretId' => $uploadConfig['upload_access_key'],
            'secretKey' => $uploadConfig['upload_secret_key'],
            'bucket' => $uploadConfig['upload_bucket'],
            'region' => $uploadConfig['upload_url'],
            'durationSeconds' => 3600,
            'allowPrefix' => '*',
            'allowActions' => [
                'name/cos:PutObject',
                'name/cos:PostObject',
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ]
        ];
        try {
            $data = $sts->getTempKeys($config);
            return [
                'tmpSecretId' => $data['credentials']['tmpSecretId'],
                'tmpSecretKey' => $data['credentials']['tmpSecretKey'],
                'sessionToken' => $data['credentials']['sessionToken'],
                'startTime' => time(),
                'expiredTime' => $data['expiredTime']
            ];
        } catch (Exception $e) {
            $error = json_decode($e->getMessage(),true);
            return [
                'error' => 1,
                'code' => $error['Error']['Code'],
                'message' => $error['Error']['Message']
            ];
        }
    }

    public function enable()
    {
        Config::addConfigGroup('upload', '上传配置');
    }

    public function disable()
    {
        Config::whereIn('name', ['upload_mode', 'upload_bucket', 'upload_access_key', 'upload_secret_key', 'upload_url', 'upload_cdn_url'])->delete();
        Config::removeConfigGroup('upload');
    }
}